package com.lc.servlet;

import com.lc.bean.Menu;
import com.lc.bean.Role;
import com.lc.service.MenuService;
import com.lc.service.RoleService;
import com.lc.service.impl.MenuServiceImpl;
import com.lc.service.impl.RoleServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @description:查询所有列表和相应角色所对应的权限菜单的servlet
 * @author: ManolinCoder
 * @time: 2021/8/25
 */
@WebServlet("/power/role/getRoleAndMenu")
public class RoleAndItsMenuServlet extends HttpServlet {
    private MenuService menuService = new MenuServiceImpl();
    private RoleService roleService = new RoleServiceImpl();
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取数据
        String roleId = req.getParameter("roleId");
        //调用service方法
        //1.查询所有菜单，只有目前存在的菜单才在修改页面中显示
        List<Menu> menuList = menuService.getMenuList();//只有菜单信息没有与角色的联系

        //保存筛选结果的菜单列表
        List<Menu> finalMenus = new ArrayList<>();

        //2.查询相应角色所对应的权限菜单
        List<Integer> roleAndItsMenu = roleService.getRoleAndItsMenu(Integer.parseInt(roleId));

        //3.主键查询角色信息
        Role roleById = roleService.getRoleById(Integer.parseInt(roleId));

        for (Integer andItsMenu : roleAndItsMenu) {
            //与所有一级和二级菜单的id进行比较，存在的就赋值
            for (Menu menu : menuList) {
                if (andItsMenu == menu.getMenuId()) {
                    finalMenus.add(menu);
                }
                for (Menu menu2 : menu.getSecondMenuList()) {
                    if (andItsMenu == menu2.getMenuId()) {
                        List<Menu> newMenu2 = new ArrayList<>();
                        newMenu2.add(menu2);
                        menu.setSecondMenuList(newMenu2);
                    }
                }
            }
        }


        req.setAttribute("menuList",finalMenus);
        req.setAttribute("roleId",roleId);
        req.setAttribute("roleName",roleById.getRoleName());
        req.setAttribute("roleState",roleById.getRoleState());
        req.getRequestDispatcher("edit.jsp").forward(req,resp);
    }
}
